﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yz.Base;
using Yz.Core.Extensions;
using Yz.Core.Tools;

namespace Yz.FileService.Middlewares
{
    public class PreviewMiddleware : BaseUploadMiddleware, IMiddleware
    {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            context.Response.ContentType = "application/json; charset=utf-8";
            #region 跨域上传
            if (context.Request.Method.Equals(HttpMethods.Options, StringComparison.OrdinalIgnoreCase))
            {
                base.AddHttpOptionHeader(context);
            }
            #endregion

            #region 后台post上传
            else if (context.Request.Method.Equals(HttpMethods.Get, StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    #region 验证token
                    await ValidateTokenAsync(context);
                    context.Request.Headers.TryGetValue("appId", out StringValues appId);
                    #endregion

                    string fileId = context.Request.Query["id"];
                    if (string.IsNullOrEmpty(fileId))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            msg = "您要预览的文件不存在！"
                        }.ToJson());
                        return;
                    }
                    string flPath = fileId.ToDes3Decrypt();
                    string filePhysicalPath = _uploadConfig.PhysicalPath + flPath;
                    string filePath = _uploadConfig.VirtualPath + flPath;
                    string ext = Path.GetExtension(filePhysicalPath).ToLower();
                    if (!filePhysicalPath.Contains(appId))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            msg = "您没有权限访问此文件！"
                        }.ToJson());
                        return;
                    }
                    if (!FileTypeList.DocList.Contains(ext))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            msg = "此文件不支持预览！"
                        }.ToJson());
                        return;
                    }
                    if (!File.Exists(filePhysicalPath))
                    {
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            msg = "您要预览的文件不存在！"
                        }.ToJson());
                        return;
                    }
                    context.Response.ContentType = "text/html";
                    if (ext == ".pdf")//pdf文件预览
                    {
                        filePath = "/FileNode1/0726445878/2021/01/28/966c638a72a34ee2878484d55cca7684.pdf";
                        string content = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "/Htmls/pdf.html", Encoding.UTF8).Replace("$fileUrl$", filePath);
                        await context.Response.WriteAsync(content, Encoding.UTF8); 
                    }
                    else if (ext == ".docx")
                    {
                        filePath = "/YzFile/0726445878/2021/01/28/20e4d1cf1dd441fea80129100ab1b6bc.docx";
                        string wordHtmlPath = "/YzFile/0726445878/2021/01/28/20e4d1cf1dd441fea80129100ab1b6bc.html";
                        string wordHtml = YzWord.ToHtml(filePath);// ce.office.extension.WordHelper.ToHtml(filePath);
                        using (var fileStream = new FileStream(wordHtmlPath, FileMode.Create))
                        {
                            byte[] data = Encoding.UTF8.GetBytes(wordHtml);
                            fileStream.Write(data, 0, data.Length);
                        }
                        await context.Response.WriteAsync(wordHtml, Encoding.UTF8);
                    }
                    else if (ext == ".xlsx")
                    {
                        filePath = "/YzFile/0726445878/2021/01/28/591de2ed5032423e912d9b45ad0dc5c7.xlsx";
                        string excelHtmlPath = "/YzFile/0726445878/2021/01/28/591de2ed5032423e912d9b45ad0dc5c7.html";
                        string excelHtml = ce.office.extension.ExcelHelper.ToHtml(filePath);
                        using (var fileStream = new FileStream(excelHtmlPath, FileMode.Create))
                        {
                            byte[] data = Encoding.UTF8.GetBytes(excelHtml);
                            fileStream.Write(data, 0, data.Length);
                        }
                        await context.Response.WriteAsync(excelHtml, Encoding.UTF8);
                    }
                    else
                    {
                        context.Response.ContentType = "application/json; charset=utf-8";
                        await context.Response.WriteAsync(new VmUpFileBase()
                        {
                            msg = "文件预览失败！"
                        }.ToJson());
                    }
                    return;
                }
                catch (Exception ex)
                {
                    context.Response.ContentType = "application/json; charset=utf-8";
                    YzNLog.Error(ex);
                    await context.Response.WriteAsync(new VmUpFileBase()
                    {
                        msg = "文件预览失败"
                    }.ToJson());
                }
            }
            #endregion

            #region 非法上传
            else
            {
                await base.AddHttpNotAllowedAsync(context);
            }
            #endregion 
        }
    }
}
